<?php
/**
 * @package     nuo
 * @subpackage  nuo.route
 * @author      Nam Nguyen <nam.ngvan@gmail.com>
 * @version     1.0
 * @since       Apr 17, 2013
 */
class Nuo_Route_Alias extends Nuo_Route_Abstract
{
	/**
	 * @param Request $request
	 * @param array $parts
	 * @return bool
	 */
	function match($request, $parts)
	{
		$db = Database::instance();

		$lists = array();

		foreach ($parts as $value)
		{
			$lists[$value] = $db -> quote($value, 'string');
		}

		$lists = implode(',', $lists);

		$sql = "SELECT * FROM nuo_route_alias WHERE alias_id IN ($lists)";

		$rows = $db -> fetchAll($sql);

		if (!$rows)
		{
			return;
		}
	
		/**
		 * find all action from route as type.
		 */
		$maps1 = array();
		$params = array();

		if ($rows)
		{
			foreach ($rows as $row)
			{
				$maps1[$row['alias_id']] = $row;
				$params[$row['data_pk']] = $row['data_id'];
			}
		}
		
		$maps2 = array();
		$mapParts = array();
		
		foreach ($parts as $value)
		{
			if (isset($maps1[$value]))
			{
				$mapParts[] = '$'. $maps1[$value]['data_type'];
			}else
			{
				$mapParts[] = $value;
			 }
		}
		/**
		 * match first.
		 */
		$dataType  = $mapParts[0];
		$sql = "SELECT path, action FROM nuo_route_action WHERE data_type = '$dataType'";
		$actions  =  $db->fetchPairs($sql);
		
		$path = '';
		$route = '';
		
		foreach($mapParts as $part)
		{
			$path .= $part;
			if(isset($actions[$path]))
			{
				$route = $actions[$path];
			}else{
				break;
			}
			$path .='/';
		}
		if ($route)
		{
			
			if(($pos = strpos($route,'?')) > 0)
			{
				$q =  substr($route, $pos+1);
				$route  =  substr($route,0,$pos);
				
				// build params
				$p =  explode('=', $q);
				$max  = count($p)-1;
				for($i =0; $i<$max;++$i){
					$params[$p[$i]] =  $p[$i+1];
				}
			}
						
			$dir = Nuo::getRouter()->getDir();
			$name  =  str_replace('@', $dir, $route);
			$request -> setName($name);
			$request -> setParams($params);
			return TRUE;
		}
		return FALSE;
	}
}
